package com.sen.app.timemail.quartz;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.sen.app.timemail.entity.RecipientInfoEntity;
import com.sen.app.timemail.services.SendEmailService;
import com.sen.app.timemail.utils.EnvUtils;
import com.sen.app.timemail.utils.logs.AppLogger;
import com.sen.app.timemail.utils.logs.AppLogs;

/**
 * 发送邮件任务调度器
 * 
 * @author sen
 */
public class SendEmailQuartzJob extends QuartzJobBean implements StatefulJob {
	
	/** 日志记录器 */
	private static Logger logger = Logger.getLogger(SendEmailQuartzJob.class);
	
	/**
	 * 记录所有需要发送的邮箱
	 */
	private static AppLogger SEND_LIST_LOG = AppLogs.SEND_LIST_LOG;
	
	/** 
	 * 记录发送成功的email
	 */
	private static AppLogger SEND_SUCCESS_LOG = AppLogs.SEND_SUCCESS_LOG;
	
	/** 
	 * 记录发送失败的email
	 */
	private static AppLogger SEND_FAIL_LOG = AppLogs.SEND_FAIL_LOG;
	
	/**
	 * 缓存所有接收者
	 */
	private static List<RecipientInfoEntity> cache;
	
	/**
	 * 发送邮件service，可通过spring注入
	 */
	public SendEmailService sendEmailService;
	
	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		if (logger.isInfoEnabled()) logger.info("开始发送邮件.");
		
		initCache();
		
		if (CollectionUtils.isEmpty(cache)) {
			if (logger.isInfoEnabled()) logger.info("未找到接受者,取消发送.");
		} else {
			RecipientInfoEntity info = cache.get(0);
			
			if (logger.isInfoEnabled())
				logger.info("正在发送邮件到[".concat(info.getEmailAddr()).concat("]."));
			
			String retVal = sendEmailService.sendTo(info);
			
			if (StringUtils.isNotBlank(retVal)) {
				if (logger.isInfoEnabled()) logger.info("Success!");
				
				// 发送成功记录到sendSuccess.log文件中
				SEND_SUCCESS_LOG.info(info.getFirstName() + EnvUtils.ATTR_SEPA  
						+ info.getLastName() + EnvUtils.ATTR_SEPA + info.getEmailAddr());
			} else {
				if (logger.isInfoEnabled()) logger.info("Fail!");
				
				// 发送成功记录到sendFail.log文件中
				SEND_FAIL_LOG.info(info.getFirstName() + EnvUtils.ATTR_SEPA
						+ info.getLastName() + EnvUtils.ATTR_SEPA + info.getEmailAddr());
			}
			cache.remove(0);
			logger.info("还剩".concat(String.valueOf(cache.size())).concat("个待发送!\n"));
		}
	}
	
	/**
	 * 缓存数据
	 */
	private void initCache() {
		if (null == cache) {
			cache = sendEmailService.getAllRecipientEmail();
			if (logger.isDebugEnabled()) 
				logger.debug("本次缓存数据总个数".concat(cache.size()+"."));
			
			// 记录所有待发送的邮箱地址
			if (CollectionUtils.isNotEmpty(cache)) {
				for (RecipientInfoEntity row : cache) {
					SEND_LIST_LOG.info(row.getFirstName().concat("|")
						.concat(row.getLastName()).concat("|")
						.concat(row.getEmailAddr()));
				}
			}
		}
	}

	public SendEmailService getSendEmailService() {
		return sendEmailService;
	}

	public void setSendEmailService(SendEmailService sendEmailService) {
		this.sendEmailService = sendEmailService;
	}
}
